﻿using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.WowAddonStudio.FrameXml.Design.Serialization;

namespace Microsoft.WowAddonStudio.FrameXml.Editor.Serialization
{
    public class TextLinesFrameXmlSerializer : FrameXmlSerializer
    {
        private readonly IVsTextLines textLines;

		/// <summary>
		/// Initializes a new instance of the <see cref="TextLinesFrameXmlSerializer"/> class.
		/// </summary>
		/// <param name="textLines">The text lines.</param>
		/// <param name="documentMokiner">The document mokiner.</param>
        public TextLinesFrameXmlSerializer(IVsTextLines textLines, string documentMokiner)
        {
            if (textLines == null)
                throw new ArgumentNullException("textLines");

            this.textLines = textLines;
			DocumentMoniker = documentMokiner;
        }

        /// <summary>
        /// Reads the FrameXML.
        /// </summary>
        /// <returns>
        /// A <see cref="String"/> containing the FrameXML.
        /// </returns>
        public override string ReadFrameXml()
        {
            int line, index;
            string buffer;

            if (textLines.GetLastLineIndex(out line, out index) != VSConstants.S_OK)
                return null;
            if (textLines.GetLineText(0, 0, line, index, out buffer) != VSConstants.S_OK)
                return null;

            return buffer;
        }

        /// <summary>
        /// Writes the FrameXML.
        /// </summary>
        /// <param name="frameXml">A <see cref="String"/>containing the FrameXML.</param>
        public override void WriteFrameXml(string frameXml)
        {
            int endLine, endCol;
            textLines.GetLastLineIndex(out endLine, out endCol);
            int len = (frameXml == null) ? 0 : frameXml.Length;

            // Fix location of the string
            IntPtr pText = Marshal.StringToCoTaskMemAuto(frameXml);
            try
            {
                textLines.ReplaceLines(0, 0, endLine, endCol, pText, len, null);
            }
            finally
            {
                Marshal.FreeCoTaskMem(pText);
            }
        }
    }
}
